CF 337A Puzzles (dp)

题面

time limit per test1 second memory limit per test256
megabytes inputstandard input outputstandard output The end of the
school year is near and Ms. Manana, the teacher, will soon have to say
goodbye to a yet another class. She decided to prepare a goodbye
present for her n students and give each of them a jigsaw puzzle
(which, as wikipedia states, is a tiling puzzle that requires the
assembly of numerous small, often oddly shaped, interlocking and
tessellating pieces).
The shop assistant told the teacher that there are m puzzles in the
shop, but they might differ in difficulty and size. Specifically, the
first jigsaw puzzle consists of f1 pieces, the second one consists of
f2 pieces and so on.
Ms. Manana doesn’t want to upset the children, so she decided that the
difference between the numbers of pieces in her presents must be as
small as possible. Let A be the number of pieces in the largest puzzle
that the teacher buys and B be the number of pieces in the smallest
such puzzle. She wants to choose such n puzzles that A - B is minimum
possible. Help the teacher and find the least possible value of A - B.

Input

The first line contains space-separated integers n and m
(2 ≤ n ≤ m ≤ 50). The second line contains m space-separated integers
f1, f2, …, fm (4 ≤ fi ≤ 1000) — the quantities of pieces in the
puzzles sold in the shop.

Output

Print a single integer — the least possible difference the
teacher can obtain.

Examples input

4 6
10 12 10 7 5 22

output

5

一句话题面

从m个数中找出差值最小的n个数,然后输出这个最小的差值

思路

毕竟A题,水,先排序,然后dp一下区间差值(就是区间里第i+m-1个数减去第i个数),找出最小的差值即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//kZime
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int n,m,a[55],dp[55],rs=1000;
inline int read(){
int k=0;char f=1,c=getchar();
for(;!isdigit(c);c=getchar())if(c=='-')f=-1;
for(;isdigit(c);c=getchar())k=k*10+c-'0';
return k*f;
}
int main(){
n=read();m=read();
for(int i=0;i<m;i++){
a[i]=read();
}
sort(a,a+m);
// for(int i=0;i<m;i++)cout<<a[i]<<" ";
// cout<<endl;
for(int i=0;i<m-n+1;i++){
dp[i]=a[i+n-1]-a[i];
rs=min(rs,dp[i]);
}
printf("%d",rs);
return 0;
}